<?php

namespace App\Console\Commands\OpenShop\Nsq;


use App\Enums\Check\CheckEnum;
use App\Http\Middleware\OpenShop\UserPermissionAuth;
use App\Library\Rms\RmsShopApi;
use App\Models\Appraise\AppraiseMessageTaskModel;
use App\Models\Appraise\AppraiseModel;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderPayHistoryModel;
use App\Service\Activity\ShopActivityService;
use App\Service\Common\FsCardService;
use App\Service\OpenShop\Feishu\BaseService;
use App\Service\OpenShop\Feishu\ShopTagsService;
use App\Service\WorkOrder\Appraise\NotifyService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Kuafu\Nsq\NsqSubscriber;
use NSQClient\Contract\Message;

class NsqSubOpenShopKfosPaidTagsCommand extends Command
{
    protected $signature = 'openshop:nsq-sub-openshop-kfos-paid-tags';

    protected $description = 'NSQ接受订货支付状态处理';

    public function handle()
    {
        ini_set('memory_limit', '4G');
        (new NsqSubscriber(config('nsq.default.address')))
            ->sub('kfos.order.merchantOrder.fullPaid', 'openShop.kfos.delivery.note.tags',
                function (Message $message) {
                    $data = $message->data();
                    Log::info('NSQ当前内存占用：' . (memory_get_usage(true) / 1024 / 1024) . "MB\t" . json_encode($data, JSON_UNESCAPED_UNICODE));

                    if (!($data['shop_id'] ?? 0)) {
                        $message->done();
                        return;
                    }

                    $mainProcessModel = OpenShopMainProcessModel::query()
                                                                ->where('shopId', $data['shop_id'])
                                                                ->first();
                    if (!$mainProcessModel) {
                        $message->done();
                        return;
                    }

                    // 设备费
                    if ($data['sys_type'] == CheckEnum::SYS_TYPE_OPEN_SHOP_EQUIPMENT ) {
                        (new ShopTagsService($mainProcessModel->orderNo))->updateKfosTag();

                        $message->done();
                        return;
                    }

                    // 工服
                    if ($data['sys_type'] == CheckEnum::SYS_TYPE_WORK_CLOTHES) {

                        // 订单完全支付
                        if ($data['status'] == 2) {

                            // 飞书机器人通知筹备
                            $shop = (new RmsShopApi())->getShopByIds([$mainProcessModel->shopId])['data']['shopList'][0] ?? [];

                            // 筹备
                            $uid = (int)OpenShopOrderManagerModel::getManagerUid($mainProcessModel->id, OpenShopOrderManagerModel::MANAGER_TYPE_4);

                            (new FsCardService())
                                ->setPath(FsCardService::PATH_GENERAL_V3)
                                ->buildElementField("**订货单号：**\n" .$data['code'] ?? '')
                                ->buildElementField("**订单金额：**\n" . '￥'.($data['total_amount'] ?? 0))
                                ->buildElementField("**门店编号：**\n" . $shop['shopCode'] ?? 0)
                                ->buildElementField("**门店名称：**\n" . $shop['name'] ?? '')
                                ->buildElementField("**处理时间：**\n" . date('Y-m-d'))
                                ->setWildCardData(
                                    [
                                        'title' => '【完成通知】商家工服已支付',
                                        'url'   => BaseService::getOrderInfoWebAppUrl($mainProcessModel->orderNo),
                                    ]
                                )
                                ->replace(true)
                                ->setKfUserIds([$uid])
                                ->setModule(UserPermissionAuth::MODULE_OPEN_SHOP)
                                ->baseSend();

                            (new ShopTagsService($mainProcessModel->orderNo))->updateWorkClothes();
                        }

                        $message->done();
                        return;
                    }


                    // 软装费
                    // 1. 开店阶段到达筹备阶段，设计完成整套图设计，且加盟商支付软装费用支付后，系统自动发起「门店设计」评价反馈通知
                    // 2. 需要注意：如果是系统跳流程，如该节点未涉及到设计费（设计费用）用支付，不需要进行推送「门店设计」评价反馈通知
                    if ($data['sys_type'] == CheckEnum::SYS_TYPE_OPEN_SHOP_DECORATE) {

                        // 查询是否存在设计费支付记录
                        $shopDesignPayCount = OpenShopSignOrderPayHistoryModel::query()
                            ->where("orderNo", $mainProcessModel->orderNo)
                            ->where("sysType", CheckEnum::SYS_TYPE_OPEN_SHOP_DESIGN)
                            ->where("payStatus", OpenShopSignOrderPayHistoryModel::PAY_STATUS_OK)
                            ->count();

                        if ($shopDesignPayCount) {

                            // 查询评价推送记录
                            $taskCount = AppraiseMessageTaskModel::query()
                                ->where('shopId', $mainProcessModel->shopId)
                                ->where('type', AppraiseModel::TYPE_APP_SHOP_DESIGN)
                                ->count();

                            if (!$taskCount) {

                                // 商家App评价信息通知
                                NotifyService::notify($mainProcessModel->orderNo, AppraiseModel::TYPE_APP_SHOP_DESIGN, 0, $mainProcessModel->shopId);
                            }
                        }


                        $message->done();
                        return;
                    }

                    // 商家app订货--关联活动
                    if ($data['sys_type'] == CheckEnum::SYS_TYPE_ROS) {
                        Log::info(
                            'debug_activity_order_pay_suc', [
                                'data' => $data,
                            ]
                        );

                        // 订单完全支付
                        if ($data['status'] == 2) {
                            $orderId     = $data['id'];                                            // 订货单id
                            $code        = $data['code'];                                          // 订货单编号
                            $uuid        = $data['uuid'] ?? '';                                    // 活动 - 门店参与uuid
                            $payUserid   = $data['new_orders_step_payments'][0]['uid'] ?? 0;       // 支付人id
                            $payUserName = $data['new_orders_step_payments'][0]['username'] ?? ''; // 支付人名字
                            $address     = '';                                                     // 订单地址
                            $payTime     = $data['pay_time'] ? strtotime($data['pay_time']) : 0;   // 支付时间

                            if ($uuid) {
                                ShopActivityService::orderPaymentCompletedAfter($orderId, $code, $uuid, $payUserid, $payUserName, $address, $payTime);
                            }
                        }

                        $message->done();
                        return;
                    }
                    $message->done();
                });

    }
}
